<template>
    <div>
        <el-form ref="form"  :model="form" :rules="rules" label-width="120px">
            <el-form-item label="角色名称" prop="name">
                <el-input v-model="form.name" placeholder="1-10个字符" style="width: 80%;"></el-input>
            </el-form-item>
            <el-form-item label="角色描述" prop="description">
                <el-input v-model="form.description" placeholder="1-20个字符" style="width: 80%;"></el-input>
            </el-form-item>
        </el-form>
        <div slot="footer" class="dialog-footer">
            <el-button @click="cancelClick">取 消</el-button>
            <el-button type="primary" @click="confirmClick">确 定</el-button>
        </div>
    </div>
</template>

<script>
import { addRole, updateRole } from '@/api/setting'

export default {
    name: 'AddRole',
    props: {
        title: {
            type: String,
            required: true
        }
    },
    data() {
        return {
            form: {
                name: '',
                description: ''
            },
            rules: {
                name: [
                    {required: true, message: '请输入角色名称', trigger: 'blur'},
                    {min: 1, max: 10, message: '长度在1-10个字符', trigger: 'blur'}
                ],
                description: [
                    {required: true, message: '请输入角色描述', trigger: 'blur'},
                    {min: 1, max: 20, message: '长度在1-20个字符', trigger: 'blur'}
                ]
            }
        }
    },
    methods: {
        // 确认操作
        confirmClick() {  
            this.$refs['form'].validate(async (valid) => {
                if(valid) {
                    // 校验通过
                    if(this.title === '新增角色') {
                        // 新增操作
                        await addRole(this.form)
                        this.$message.success('新增角色成功')
                    } else {
                        // 编辑操作
                        await updateRole(this.form)
                        this.$message.success('编辑角色成功')
                    }
                    this.$emit('confirmClick')
                } else {
                    // 校验失败
                    console.log('校验未通过');
                    return false;
                }
            })
        },
        // 取消操作
        cancelClick() {
            this.form = {
                name: '',
                description: ''
            }
            this.$refs['form'].resetFields()
            this.$emit('cancelClick')
        }
    }
}
</script>

<style></style>